#!/bin/sh

AUTO_RUN_DIR="/data/auto_run"
LOADER_NAME="auto_run.sh"

auto_run() {
    # auto run script at startup.
    echo -e "\033[32mSearching for scripts...\033[0m"
    cd "$AUTO_RUN_DIR" || {
        echo -e "\033[31mError: Cannot access $AUTO_RUN_DIR\033[0m" >&2
        return 1
    }
    for script in *.sh; do
        [ "$script" = "$LOADER_NAME" ] && continue
        echo -e "\033[33m- Executing: $script...\033[0m"
        if ! /bin/sh "$script"; then
            echo -e "\033[31m- Error: Failed to execute $script\033[0m" >&2
        fi
    done
    echo -e "\033[32mAuto run scripts completed!\033[0m"
}

enable() {
    # Add script to system autostart
    uci set firewall.auto_run=include
    uci set firewall.auto_run.type='script'
    uci set firewall.auto_run.path="${AUTO_RUN_DIR}/${LOADER_NAME}"
    uci set firewall.auto_run.enabled='1'
    uci add firewall rule
    uci set firewall.@rule[-1].name='Allow auto_run'
    uci set firewall.@rule[-1].src='lan'
    uci set firewall.@rule[-1].src_ip='0.0.0.1'
    uci set firewall.@rule[-1].proto='all'
    uci set firewall.@rule[-1].target='ACCEPT'
    uci set firewall.@rule[-1].enabled='1'
    uci commit firewall
    /etc/init.d/firewall restart
    if ! iptables -L -v -n | grep "Allow auto_run"; then
        echo -e "\033[33m- Firewall start failed! Adding cron task...\033[0m"
        echo "*/1 * * * * /bin/sh /data/auto_run/auto_run.sh >> /tmp/log/auto_run.log 2>&1" >> /etc/crontabs/root
    fi
    echo -e "\033[32mauto_run has been enableed!\033[0m"
}
disable() {
    # Remove scripts from system autostart
    uci delete firewall.auto_run
    uci delete firewall.$(uci show firewall | awk -F'[.=]' '/Allow auto_run/ {print $2; exit}')
    uci commit firewall
    /etc/init.d/firewall restart
    if grep "auto_run.sh" /etc/crontabs/root; then
        sed -i "\#auto_run.sh#d" /etc/crontabs/root
    fi
    echo -e "\033[33mauto_run has been removed!\033[0m"
}
main() {
    if [ -e "/tmp/log/auto_run.log" ]; then
        exit 0
    fi
    case $1 in
        "") auto_run ;;
        enable) enable ;;
        disable) disable ;;
        *) echo -e "\033[31mUnknown parameter: $1\033[0m"; return 1 ;;
    esac
}
main "$@"